﻿/*
* DataManager.cpp
*
* 数据管理
*
* create date: 2014.4.21
* create by: leo
*
*/

#include "DataManager.h"

#include <string>
#include "cocos-ext.h"
#include "spine\Json.h"
#include "FilePathProvider.h"
#include "CampaignInfo.h"

using namespace std;
USING_NS_CC;
USING_NS_CC_EXT;

CDataManager* CDataManager::Instance = NULL;

CDataManager& CDataManager::getInstance()
{
	if (NULL == Instance)
	{
		Instance = new CDataManager();
		Instance->initWithFile("game_config.json");
	}
	return *Instance;
}

void CDataManager::registerProvider(const char* name, CDataProvider& provider)
{
	mProvDict.setObject(&provider, name);
}

CDataProvider* CDataManager::getProvider(const char* name)
{
	CDataProvider* prov = (CDataProvider*)mProvDict.objectForKey(name);
	return prov;
}

CDataManager::CDataManager()
{}

CDataManager::~CDataManager()
{}

bool CDataManager::initWithFile(const char* filePath)
{
	CFilePathProvider& fpProv = CFilePathProvider::getInstance();
	registerProvider("FilePath", fpProv);

	string filePathStr = filePath;
	size_t startPos = filePathStr.find_last_of(".");
	string suffix = &filePathStr[startPos+1];
	if (0 == suffix.compare("json"))
	{
		const char* config = CFileReader::CreateStringFromFile(fpProv.getFilePath(filePath).getCString());
		Json* root = Json_create(config);
		Json* item = Json_getItem(root, CCampaignInfo::JSON_LABEL);
		const char* itemInfo = item->valuestring;

		CCampaignInfo* campaignInfo = new CCampaignInfo();
		campaignInfo->initWithFile(itemInfo);
		registerProvider("Campaign", *campaignInfo);
		return true;
	}
	else
	{
		return false;
	}

	return false;
}
